//
//  BZHttpFileHelper.m
//  BaseSwift
//
//  Created by gh on 2019/10/15.
//  Copyright © 2019 ghwang. All rights reserved.
//

#import "BZHttpFileHelper.h"
#import <AliyunOSSiOS/OSSService.h>
#import "BaseSwift-Swift.h"
#import <AVFoundation/AVFoundation.h>
#import "JZLocationConverter.h"

//#define ACCKEY @"LTAIEvdfdSQEFmB0"
//#define ACCSECRET @"nVdPh3ttBt5cRkCZ546htqFzopzUev"
//#define ENDPOINT @"https://oss-cn-shanghai.aliyuncs.com"
//#define BUCKETNAME @"vvtale-image"
//#define OSS_PREFIX @"https://vvtale-image.oss-cn-shanghai.aliyuncs.com"
//#define SERVER_IMAGE_ROOT @"hqc"


#define ACCKEY @"LTAI5xuAO1OGjUEU"
#define ACCSECRET @"gtuLFgHkNMYjNAQLd7ICc2lrSf0Ms7"
#define ENDPOINT @"http://oss-cn-beijing.aliyuncs.com"
#define BUCKETNAME @"hqctv"
#define OSS_PREFIX @"https://hqctv.oss-cn-beijing.aliyuncs.com"
#define SERVER_IMAGE_ROOT @"hqctv"

#define KCompressibilityFactor 1280.00

@interface BZHttpFileHelper ()

@property(nonatomic,strong) OSSClient * client;

@end


@implementation BZHttpFileHelper

+(instancetype)fileHelperShareInstance{
    static BZHttpFileHelper * fileHelper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fileHelper = [[BZHttpFileHelper alloc] init];
        [fileHelper initAliClient];
    });
    return fileHelper;
}

-(void)initAliClient{
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:ACCKEY                                                                                                    secretKey:ACCSECRET];

    OSSClientConfiguration * conf = [OSSClientConfiguration new];

    // 网络请求遇到异常失败后的重试次数
    conf.maxRetryCount = 3;

    // 网络请求的超时时间
    conf.timeoutIntervalForRequest =30;

    // 允许资源传输的最长时间
    conf.timeoutIntervalForResource =24 * 60 * 60;

    // 你的阿里地址前面通常是这种格式 ：http://oss……
    self.client = [[OSSClient alloc] initWithEndpoint:ENDPOINT credentialProvider:credential];
}

-(void)uploadAmr:(NSData *)amrData amrName:(NSString *)amrName callback:(void (^)(id succResult))callBack{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = BUCKETNAME;
    put.objectKey = [NSString stringWithFormat:@"%@/%@",SERVER_IMAGE_ROOT,amrName];
    put.uploadingData = amrData; // 直接上传NSData
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@/%@",OSS_PREFIX,SERVER_IMAGE_ROOT,amrName];
    put.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };

    OSSTask * putTask = [self.client putObject:put];

    // 上传阿里云
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");

            callBack(fullPath);
            
            
            OSSPutObjectResult * result = task.result;
            NSLog(@"Result - requestId: %@, headerFields: %@, servercallback: %@",
            result.requestId,
            result.httpResponseHeaderFields,
            result.serverReturnJsonString);

        } else {

            NSLog(@"upload object failed, error: %@" , task.error);
            callBack(@"error");

            dispatch_async(dispatch_get_main_queue(), ^{
                
                [ToastUtil showWithMsg:@"文件上传失败"];
            });
        }
        return nil;
    }];
}
-(void)downloadFile:(NSString *)filename callback:(void (^)(NSData *, BOOL))callback{
    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    request.bucketName = @"savemoney";
    request.objectKey = filename;
    OSSTask * getTask = [self.client getObject:request];
    [getTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"download object success!");
            OSSGetObjectResult * getResult = task.result;
            if (callback) {
                callback(getResult.downloadedData,YES);
            }
        } else {
            NSLog(@"download object failed, error: %@" ,task.error);
            if (callback) {
                callback(nil,NO);
            }
        }
        return nil;
    }];
}
+(NSURL *)photourlWithUrlString:(NSString *)url{
    //原图
    return [NSURL URLWithString:[NSString stringWithFormat:@"http://savemcdn.dewtip.com/%@",url]];
}

+(NSURL *)s_photourlWithUrlString:(NSString *)url{
//120*120的图片
    return [NSURL URLWithString:[NSString stringWithFormat:@"http://savemcdn.dewtip.com/%@?x-oss-process=image/resize,w_120,h_120",url]];
}

+(NSURL *)s_chatPhotourlWithUrlString:(NSString *)url{
//
    return [NSURL URLWithString:[NSString stringWithFormat:@"http://savemcdn.dewtip.com/%@?x-oss-process=image/resize,m_lfit,h_200,w_200",url]];
}

- (void)gotoMap:(NSString*)lat longt:(NSString*)longt addr:(NSString*)adr type:(NSString*)type{
    // 后台返回的目的地坐标是百度地图的
    // 百度地图与高德地图、苹果地图采用的坐标系不一样，故高德和苹果只能用地名不能用后台返回的坐标
    CGFloat latitude  = lat.floatValue;  // 纬度
    CGFloat longitude = longt.floatValue; // 经度
    NSString *address = adr; // 送达地址
    
    if ([type isEqualToString:@"baidu"]) {
        
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
            // 百度地图
            // 起点为“我的位置”，终点为后台返回的坐标
            NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=%f,%f&mode=riding", latitude, longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:urlString];
            [[UIApplication sharedApplication] openURL:url];
            
        }else{
            
            [ToastUtil showWithMsg:@"请先安装百度地图"];

        }
        
    }else if ([type isEqualToString:@"qqmap"]){
        
        if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]])    {
               
            NSString *urlString = [[NSString stringWithFormat:@"qqmap://map/routeplan?type=drive&from=我的位置&to=%@&tocoord=%f,%f&policy=1&referer=%@", address, latitude,longitude,@"好去处"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSLog(@"%@",urlString);
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
               
        }else{
            
            [ToastUtil showWithMsg:@"请先安装腾讯地图"];

        }
    }else if ([type isEqualToString:@"google"]){
        
        if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {

            NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",@"好去处",@"comgooglemaps",latitude, longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSLog(@"%@",urlString);
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }else{
           
            [ToastUtil showWithMsg:@"请先安装谷歌地图"];

        }
        
    }else if ([type isEqualToString:@"gaode"]){
        
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
            // 高德地图
            // 起点为“我的位置”，终点为后台返回的address
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=BGVIS1&sname=%@&did=BGVIS2&dname=%@&dev=0&t=0",@"我的位置",address] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        }else{
            
            [ToastUtil showWithMsg:@"请先安装高德地图"];

            
        }
        
        
    }else if ([type isEqualToString:@"ios"]){
        
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com"]]){
            
            NSString *urlString = [[NSString stringWithFormat:@"http://maps.apple.com/?daddr=%@",address] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

        }else{
            
            [ToastUtil showWithMsg:@"请先安装苹果地图"];

        }
        
        
    }
    
    // 打开地图的优先级顺序：百度地图->高德地图->苹果地图
    /*if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        // 百度地图
        // 起点为“我的位置”，终点为后台返回的坐标
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=%f,%f&mode=riding", latitude, longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlString];
        [[UIApplication sharedApplication] openURL:url];
        
    }else if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        // 高德地图
        // 起点为“我的位置”，终点为后台返回的address
        NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=BGVIS1&sname=%@&did=BGVIS2&dname=%@&dev=0&t=0",@"我的位置",address] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }else if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com"]]){
        // 苹果地图
        // 起点为“我的位置”，终点为后台返回的address
        NSString *urlString = [[NSString stringWithFormat:@"http://maps.apple.com/?daddr=%@",address] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }else{
        // 快递员没有安装上面三种地图APP，弹窗提示安装地图APP

        [ToastUtil showWithMsg:@"请安装地图APP 建议安装百度地图APP"];
    }*/
}
- (NSString *)htmlForJPGImage:(UIImage *)image{
    
    NSData *imageData = UIImageJPEGRepresentation(image,1.f);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
    return [NSString stringWithFormat:@"<div align=center><img src='%@' /></div>", imageSource];
    
}
- (NSString*)htmlForImgPath:(NSString*)url{
    
    NSString *html = [NSString stringWithFormat:@"<div align=center><img src='%@' /></div>",url];
    NSString *content = [NSString stringWithFormat:@"<html><body>%@</body></html>", html];
    return content;
}


- (UIImage *)getJPEGImagerImg:(UIImage *)image{
    CGFloat oldImg_WID = image.size.width;
    CGFloat oldImg_HEI = image.size.height;
    //CGFloat aspectRatio = oldImg_WID/oldImg_HEI;//宽高比
    if(oldImg_WID > KCompressibilityFactor || oldImg_HEI > KCompressibilityFactor){
        //超过设置的最大宽度 先判断那个边最长
        if(oldImg_WID > oldImg_HEI){
            //宽度大于高度
            oldImg_HEI = (KCompressibilityFactor * oldImg_HEI)/oldImg_WID;
            oldImg_WID = KCompressibilityFactor;
        }else{
            oldImg_WID = (KCompressibilityFactor * oldImg_WID)/oldImg_HEI;
            oldImg_HEI = KCompressibilityFactor;
        }
    }
    UIImage *newImg = [self imageWithImage:image scaledToSize:CGSizeMake(oldImg_WID, oldImg_HEI)];
    NSData *dJpeg = nil;
    if (UIImagePNGRepresentation(newImg)==nil) {
        dJpeg = UIImageJPEGRepresentation(newImg, 0.5);
    }else{
        dJpeg = UIImagePNGRepresentation(newImg);
    }
    return [UIImage imageWithData:dJpeg];
}
#pragma mark - 压缩多张图片 最大宽高1280 类似于微信算法
- (NSArray *)getJPEGImagerImgArr:(NSArray *)imageArr{
    NSMutableArray *newImgArr = [NSMutableArray new];
    for (int i = 0; i<imageArr.count; i++) {
        UIImage *newImg = [self getJPEGImagerImg:imageArr[i]];
        [newImgArr addObject:newImg];
    }
    return newImgArr;
}
#pragma mark - 压缩一张图片 自定义最大宽高
- (UIImage *)getJPEGImagerImg:(UIImage *)image compressibilityFactor:(CGFloat)compressibilityFactor{
    CGFloat oldImg_WID = image.size.width;
    CGFloat oldImg_HEI = image.size.height;
    //CGFloat aspectRatio = oldImg_WID/oldImg_HEI;//宽高比
    if(oldImg_WID > compressibilityFactor || oldImg_HEI > compressibilityFactor){
        //超过设置的最大宽度 先判断那个边最长
        if(oldImg_WID > oldImg_HEI){
            //宽度大于高度
            oldImg_HEI = (compressibilityFactor * oldImg_HEI)/oldImg_WID;
            oldImg_WID = compressibilityFactor;
        }else{
            oldImg_WID = (compressibilityFactor * oldImg_WID)/oldImg_HEI;
            oldImg_HEI = compressibilityFactor;
        }
    }
    UIImage *newImg = [self imageWithImage:image scaledToSize:CGSizeMake(oldImg_WID, oldImg_HEI)];
    NSData *dJpeg = nil;
    if (UIImagePNGRepresentation(newImg)==nil) {
        dJpeg = UIImageJPEGRepresentation(newImg, 0.5);
    }else{
        dJpeg = UIImagePNGRepresentation(newImg);
    }
    return [UIImage imageWithData:dJpeg];
}
#pragma mark - 压缩多张图片 自定义最大宽高
- (NSArray *)getJPEGImagerImgArr:(NSArray *)imageArr compressibilityFactor:(CGFloat)compressibilityFactor{
    NSMutableArray *newImgArr = [NSMutableArray new];
    for (int i = 0; i<imageArr.count; i++) {
        UIImage *newImg = [self getJPEGImagerImg:imageArr[i] compressibilityFactor:compressibilityFactor];
        [newImgArr addObject:newImg];
    }
    return newImgArr;
}
#pragma mark - 根据宽高压缩图片
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (UIImage *)screenshot:(UIViewController *) controller
{
    CGRect rect = controller.view.bounds;
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (context == NULL) return nil;
    CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
    
    //[controller layoutIfNeeded];
    [[controller.view layer] renderInContext:context];
    
    UIImage *screenshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenshotImage;
}
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}
/**
 *  截取当前屏幕 并修改
 *
 *  @return NSData *
 */
+ (UIImage *)imageWithScreenshot
{
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation))
        imageSize = [UIScreen mainScreen].bounds.size;
    else
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        if (orientation == UIInterfaceOrientationLandscapeLeft)
        {
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        }else if (orientation == UIInterfaceOrientationLandscapeRight)
        {
            CGContextRotateCTM(context, -M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
        {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        }
        else
        {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // 修改图片
    NSData *imageData = UIImagePNGRepresentation(image);
    UIImage *LastImage = [UIImage imageWithData:imageData];
    
    UIImage *img = [UIImage imageNamed:@"qrcode.jpg"];
    CGImageRef imgRef = img.CGImage;
    CGFloat w = CGImageGetWidth(imgRef);
    CGFloat h = CGImageGetHeight(imgRef);
    
    //以1.png的图大小为底图
    UIImage *img1 = LastImage;
    CGImageRef imgRef1 = img1.CGImage;
    CGFloat w1 = CGImageGetWidth(imgRef1);
    CGFloat h1 = CGImageGetHeight(imgRef1);
    
    //以1.png的图大小为画布创建上下文
    UIGraphicsBeginImageContext(CGSizeMake(w1, h1 + 255));
    [img1 drawInRect:CGRectMake(0, 0, w1, h1)];//先把1.png 画到上下文中
    [img drawInRect:CGRectMake((imageSize.width-200)/2-20, h1 + 10, 200, 200)];//再把小图放在上下文中
    
    NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;

    paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中
    
    [@"长按识别进入小程序" drawInRect:CGRectMake((imageSize.width-200)/2+190, h1+10+65, 175+300, 80) withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:50],NSForegroundColorAttributeName:[ UIColor blackColor],NSParagraphStyleAttributeName:paragraphStyle}];


    
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();//从当前上下文中获得最终图片
    UIGraphicsEndImageContext();//关闭上下文
    
    
    return  resultImg;
}
+ (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize img:(UIImage *)img

{

    
    //画布大小

    CGSize size=CGSizeMake(img.size.width,img.size.height);

    //创建一个基于位图的上下文

    UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO  scale:0.0

    

    [img drawAtPoint:CGPointMake(0.0,0.0)];

    

    //文字居中显示在画布上

    NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;

    paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中

    

    //计算文字所占的size,文字居中显示在画布上

    CGSize sizeText=[title boundingRectWithSize:img.size options:NSStringDrawingUsesLineFragmentOrigin

                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[UIColor blackColor]}context:nil].size;

    CGFloat width = img.size.width;

    CGFloat height = img.size.height;

    

    CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);

    //绘制文字

    [title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];

    

    //返回绘制的新图形

    UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

+ (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
{
    // 获取视频第一帧
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(size.width, size.height);
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
    {
        return [UIImage imageWithCGImage:img];
    }
    return nil;
}
+ (NSString *)getTopCachePath{
    
    return PYSEARCH_TOPIC_HISTORY_CACHE_PATH;
}

#define HEIGHT [ [ UIScreen mainScreen ] bounds ].size.height


+ (CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width {

  NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];

  paraStyle.lineBreakMode = NSLineBreakByWordWrapping;

  paraStyle.alignment = NSTextAlignmentLeft;

  paraStyle.lineSpacing = 6;

  paraStyle.hyphenationFactor = 1.0;

  paraStyle.firstLineHeadIndent = 0.0;

  paraStyle.paragraphSpacingBefore = 0.0;

  paraStyle.headIndent = 0;

  paraStyle.tailIndent = 0;

  NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f};

    
  CGSize size = [self boundingRectWithSize:CGSizeMake(width, HEIGHT) str:str font:font lineSpacing:6];

    return size.height;

}

+ (CGSize)boundingRectWithSize:(CGSize)size str:(NSString*)str  font:(UIFont*)font lineSpacing:(CGFloat)lineSpacing{

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;

  [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,str.length)];

 [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0,str.length)];

NSStringDrawingOptions options =NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading;

CGRect rect = [attributeString boundingRectWithSize:size options:options context:nil];//    NSLog(@"size:%@", NSStringFromCGSize(rect.size));

//文本的高度减去字体高度小于等于行间距，判断为当前只有1行

if((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {

if([self containChinese:str]) {//如果包含中文

rect =CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing);        }    }

return rect.size;
}


//判断如果包含中文
+ (BOOL)containChinese:(NSString*)str

{

  for(int i=0; i< [str length];i++){
    int a = [str characterAtIndex:i];
     if( a >0x4e00&& a <0x9fff)
    {
      return  YES;

     }

 }

      return  NO;

}

+ (CGSize)getBtnSize:(UIButton*)button{
    
    NSString *content = button.titleLabel.text;
    UIFont *font = button.titleLabel.font;
    CGSize size = CGSizeMake(MAXFLOAT, 42.0f);
    CGSize buttonSize = [content boundingRectWithSize:size
    options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
    attributes:@{ NSFontAttributeName:font}
    context:nil].size;
    

    
    return buttonSize;


}
+ (NSString*)baiduToGaodeWithLat:(double)lat longt:(double)longt{
    
    double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    double x = longt - 0.0065, y = lat - 0.006;
    double z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi);
    double theta = atan2(y, x) - 0.000003 * cos(x * x_pi);

    
    //NSLog(@"gd_lon:%f",z * cos(theta));
    //NSLog(@"gd_lat:%f",z * sin(theta));
    
    CLLocationCoordinate2D coor = CLLocationCoordinate2DMake(lat,longt);
    
    CLLocationCoordinate2D gdcoor = [JZLocationConverter bd09ToGcj02:coor];
    
    return [NSString stringWithFormat:@"%f,%f",lat,longt];
}

+ (NSString*)gaodeToBDWithLat:(double)lat longt:(double)longt{
    
    double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    double x = longt;

    double y = lat;

    double z = sqrt(x*x + y*y) + 0.00002*sin(y*x_pi);

    double theta = atan2(y, x) + 0.000003 * cos(x * x_pi);

    NSLog(@"bd_lon:%f",z * cos(theta) + 0.0065);

    NSLog(@"bd_lat:%f",z * sin(theta) + 0.006);
    CLLocationCoordinate2D coor = CLLocationCoordinate2DMake(z*sin(theta), z*cos(theta));
    
    return [NSString stringWithFormat:@"%f,%f",coor.latitude,coor.longitude];
}

@end
